//
//  ZHPageView.swift
//  ZHPageView
//
//  Created by Rango on 2020/8/26.
//  Copyright © 2020 Rango. All rights reserved.
//

import UIKit

extension ZHPageView {
    /// 重新设置选中下标,
    ///
    /// - 不要用这个方法设置默认下标!!!
    /// - 如果需要设置默认下标,在 `ZHSegmentStyle` 中设置 **defaultIndex**
    ///
    /// - Parameters:
    ///   - index: 下标
    ///   - animated: true 动画; false 无切换动画; 默认 true
    public func resetSelectedIndex(_ index: Int, animated: Bool = true) {
        assert(index >= 0 && index < titles.count, "下标越界!")
        if index < 0 || index > titles.count - 1 { return }
        if let segmentView = segmentView as? ZHSegmentView {
            segmentView.resetSelectedIndex(index, animated: animated)
        }
    }

    /// 重新加载标题和页面内容
    /// - Parameters:
    ///   - titles: 标题数组
    ///   - childVces: 子控制器数组
    ///   - defaultIndex: 默认下标
    ///   - animated: true 切换下标动画; false 无切换下标动画
    public func reloadPageView(with titles: [String], childVces: [UIViewController], defaultIndex: Int = 0, animated: Bool = true) {
        let index = defaultIndex
        assert(index >= 0 && index < titles.count, "下标越界!")
        if index < 0 || index > titles.count - 1 { return }
        
        self.titles = titles
        self.childVces = childVces
        self.style.defaultIndex = index
        self.lastIndex = index
        
        initSubviews()
    }
}

class ZHPageView: UIView {
    // MARK: - ---> Public
    /// 点选/拖拽完成后,被选中的下标值
    var didSelectedIndexClosure: ((Int) -> Void)?
    /// 点选时选中的下标值,拖拽切换的不会触发!!!
    var didTapNextIndexClosure: ((Int) -> Void)?
    /// 额外按键点击事件
    var didExtraBtnActionClosure: ((UIView) -> Void)?
    /// 隐藏、显示额外按钮
    var isHiddenExtraBtn: Bool = false {
        didSet {
            if let segmentView = segmentView as? ZHSegmentView {
                segmentView.isHiddenExtraBtn = isHiddenExtraBtn
            }
        }
    }
    /// 分栏视图
    public var segmentView = UIView()
    /// 内容视图
    public var contentView = UIView()
    // MARK: - ---> Private
    private var boundaryLine = UIView()
    private weak var parent: UIViewController? // weak 才能被正常释放
    private var style: ZHSegmentStyle = ZHSegmentStyle()
    private var childVces: [UIViewController] = []
    private var titles: [String] = []
    private var lastIndex: Int = 0 {
        didSet {
            print("ZHPageView lastIndex==\(lastIndex)")
            didSelectedIndexClosure?(lastIndex)
        }
    }
    private var nextIndex: Int = 0 {
        didSet {
            print("ZHPageView nextIndex==\(nextIndex)")
            didTapNextIndexClosure?(nextIndex)
        }
    }
    private var contentWidth: CGFloat { contentView.frame.width }
    // MARK: - ---> Life Cycle
    
    /// 初始化
    /// - Parameters:
    ///   - frame: frame description
    ///   - style: style description
    ///   - titles: titles description
    ///   - childVces: childVces description
    ///   - parent: parent description
    init(frame: CGRect,
         style: ZHSegmentStyle,
         titles: [String],
         childVces: [UIViewController],
         parent: UIViewController) {
        super.init(frame: frame)
        
        self.style = style
        self.titles = titles
        self.childVces = childVces
        self.parent = parent
        self.lastIndex = style.defaultIndex
        
        initSubviews()
    }
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        initSubviews()
        fatalError("init(coder:) has not been implemented")
    }
    deinit {
        print("\(#file)-\(#line)-\(#function)--->销毁")
    }
    /// 布局子视图
    override func layoutSubviews() {
        super.layoutSubviews()
        // TODO: 布局子视图
        let kWidth = bounds.width
        let kHeight = bounds.height
        
        let segmentViewX: CGFloat = 0
        let segmentViewY: CGFloat = 0
        let segmentViewW: CGFloat = kWidth
        let segmentViewH: CGFloat = style.height
        segmentView.frame = CGRect(x: segmentViewX, y: segmentViewY, width: segmentViewW, height: segmentViewH)
        if style.isShowShadow {
            segmentView.layer.shadowColor = style.shadowColor.cgColor
            segmentView.layer.shadowOpacity = 0.5
            segmentView.layer.shadowRadius = 0.75
            segmentView.layer.shadowOffset = CGSize(width: 0, height: 1.5)
        }
        if style.isShowBoundaryLine {
            let boundaryLineX: CGFloat = segmentViewX
            let boundaryLineY: CGFloat = segmentView.frame.maxY
            let boundaryLineW: CGFloat = segmentViewW
            let boundaryLineH: CGFloat = 0.75
            boundaryLine.frame = CGRect(x: boundaryLineX, y: boundaryLineY, width: boundaryLineW, height: boundaryLineH)
        }
        let contentViewX: CGFloat = 0
        let contentViewY: CGFloat = segmentView.frame.maxY
        let contentViewW: CGFloat = kWidth
        let contentViewH: CGFloat = kHeight - contentViewY
        contentView.frame = CGRect(x: contentViewX, y: contentViewY, width: contentViewW, height: contentViewH)
    }
    
    /// 初始化子视图
    private func initSubviews() {
        // TODO: 初始化子视图
        contentView.removeFromSuperview()
        contentView = setUpContentView()
        addSubview(contentView)
        if style.isShowBoundaryLine {
            boundaryLine.removeFromSuperview()
            boundaryLine = setUpBoundaryLine()
            addSubview(boundaryLine)
        }
        segmentView.removeFromSuperview()
        segmentView = setUpSegmentView()
        addSubview(segmentView)
    }
    
    // MARK: - ---> Lazy
    /// 分页区
    private func setUpSegmentView() -> ZHSegmentView {
        let segmentView = ZHSegmentView(frame: .zero, style: style, titles: titles)
        segmentView.didTapClosure = { [weak self] index, animated in
            guard let strongSelf = self else { return }
            strongSelf.nextIndex = index
            if let contentView = strongSelf.contentView as? ZHContentView {
                contentView.segmentItemTap(index, animated: animated)
            }
        }
        segmentView.didExtraBtnActionClosure = { [weak self] item in
            guard let strongSelf = self else { return }
            strongSelf.didExtraBtnActionClosure?(item)
        }
        return segmentView
    }
    /// 边界分割线
    private func setUpBoundaryLine() -> UIView {
        let line = UIView()
        line.backgroundColor = style.boundaryLineColor
        return line
    }
    /// 内容区
    private func setUpContentView() -> ZHContentView {
        let contentView = ZHContentView(frame: .zero, style: style, childVces: childVces, parent: parent!)
        contentView.didScrollViewDidScroll = { [weak self] scrollView, isScroll, direction in
            guard let strongSelf = self else { return }
            let offsetX = scrollView.contentOffset.x
            let scale = (offsetX / strongSelf.contentWidth)
            // 渐进式改变标题状态left
            if let segmentView = strongSelf.segmentView as? ZHSegmentView {
                segmentView.scrollStatus(with: scale, isScroll: isScroll, direction: direction)
            }
        }
        contentView.didScrollViewDidEndScrollingAnimation = { [weak self] scrollView, isScroll, lastIndex, animated in
            guard let strongSelf = self else { return }
            strongSelf.lastIndex = lastIndex
            // 保证标题居中
            if let segmentView = strongSelf.segmentView as? ZHSegmentView {
                segmentView.centerSeledted(with: lastIndex, isScroll: isScroll, animated: animated)
            }
        }
        return contentView
    }
}
